package com.departmentstore.controller;

import com.departmentstore.entity.Department;
import com.departmentstore.service.DepartmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/departments")
@Tag(name = "部门管理", description = "部门的增删改查接口")
public class DepartmentController {

    private final DepartmentService departmentService;

    @Autowired
    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @PostMapping
    @Operation(summary = "创建部门", description = "创建一个新的部门")
    public ResponseEntity<Department> createDepartment(@Valid @RequestBody Department department) {
        return ResponseEntity.ok(departmentService.createDepartment(department));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新部门", description = "根据ID更新部门信息")
    public ResponseEntity<Department> updateDepartment(
            @Parameter(description = "部门ID") @PathVariable String id,
            @Valid @RequestBody Department department) {
        department.setDepartmentId(id);
        return ResponseEntity.ok(departmentService.updateDepartment(department));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除部门", description = "根据ID删除部门")
    public ResponseEntity<Void> deleteDepartment(
            @Parameter(description = "部门ID") @PathVariable String id) {
        departmentService.deleteDepartment(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取部门", description = "根据ID获取部门信息")
    public ResponseEntity<Department> getDepartment(
            @Parameter(description = "部门ID") @PathVariable String id) {
        return ResponseEntity.ok(departmentService.getDepartmentById(id));
    }

    @GetMapping
    @Operation(summary = "获取所有部门", description = "获取所有部门的列表")
    public ResponseEntity<List<Department>> getAllDepartments() {
        return ResponseEntity.ok(departmentService.getAllDepartments());
    }

    @GetMapping("/name/{name}")
    @Operation(summary = "根据名称查找部门", description = "根据部门名称查找部门信息")
    public ResponseEntity<Department> getDepartmentByName(
            @Parameter(description = "部门名称") @PathVariable String name) {
        return ResponseEntity.ok(departmentService.getDepartmentByName(name));
    }

    @GetMapping("/manager/{managerId}")
    @Operation(summary = "根据经理ID查找部门", description = "根据经理ID查找部门信息")
    public ResponseEntity<Department> getDepartmentByManagerId(
            @Parameter(description = "经理ID") @PathVariable String managerId) {
        return ResponseEntity.ok(departmentService.getDepartmentByManagerId(managerId));
    }
} 